package com.mayjean.db.config;

import com.baomidou.mybatisplus.core.parser.ISqlParser;
import com.baomidou.mybatisplus.extension.parsers.BlockAttackSqlParser;
import com.baomidou.mybatisplus.extension.plugins.PaginationInterceptor;
import com.baomidou.mybatisplus.extension.plugins.tenant.TenantHandler;
import com.baomidou.mybatisplus.extension.plugins.tenant.TenantSqlParser;
import org.springframework.beans.factory.ObjectProvider;
import org.springframework.boot.autoconfigure.AutoConfigureAfter;
import org.springframework.boot.autoconfigure.AutoConfigureBefore;
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;

import java.util.ArrayList;
import java.util.List;

/**
 * Database configuration
 *
 * @author kyleju
 */
@Configuration
@AutoConfigureBefore({DataSourceAutoConfiguration.class})
@AutoConfigureAfter({TenantConfiguration.class})
@Import(TenantConfiguration.class)
public class DatabaseConfiguration {

	@Bean
	public PaginationInterceptor paginationInterceptor(ObjectProvider<TenantHandler> tenantHandlerObjectProvider) {
		PaginationInterceptor paginationInterceptor = new PaginationInterceptor();
		List<ISqlParser> sqlParserList = new ArrayList<>();
		sqlParserList.add(new BlockAttackSqlParser());

		tenantHandlerObjectProvider.ifAvailable(tenantHandler -> {
			TenantSqlParser tenantSqlParser = new TenantSqlParser();
			tenantSqlParser.setTenantHandler(tenantHandler);
			sqlParserList.add(tenantSqlParser);
		});

		paginationInterceptor.setSqlParserList(sqlParserList);
		return paginationInterceptor;
	}
}
